package com.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.entity.ActiveUser;
import com.service.IArticleService;

@Controller
public class LoginController extends BaseController {
	
	@Autowired
	private IArticleService articleService;
	
	/*
	 * 用户登录页面
	 */
	@RequestMapping("/login")
	public String login(Model model) throws Exception{
		
		Subject subject = SecurityUtils.getSubject();
		ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
		if(activeUser != null){
			return "redirect/first";
		}
		return "login";
	}

	/*
	 * 用户登录
	 */
	@RequestMapping("/loginsubmit")
	public String loginsubmit(Model model, HttpServletRequest request) throws Exception {
		String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
		String error = "";
		if (exceptionClassName != null) {
			if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
				// throw new CustomException("账号不存在");
				error = "账号不存在";
			} else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
				// throw new CustomException("用户名/密码错误");
				error = "用户名/密码错误";
			} else if ("randomCodeError".equals(exceptionClassName)) {
				// throw new CustomException("验证码出错");
				error = "验证码出错";
			} else {
				// throw new Exception();//最终在异常处理器生成未知错误
				error = "未知错误";
			}
		}
		model.addAttribute("error", error);
		// 此方法不处理登陆成功（认证成功），shiro认证成功会自动跳转到上一个请求路径.登陆失败还到login页面
		return "login";
	}

	/*
	 * 登录首页
	 */
	@RequestMapping("/first")
	public String first(Model model, HttpSession session) {
		try {
			// 从shiro的session中取activeUser
			Subject subject = SecurityUtils.getSubject();
			ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
			session.setAttribute("activeUser", activeUser);
			
			model.addAttribute("articleList", articleService.getArticleListByUserId(activeUser.getUserid()));
			model.addAttribute("homeName", activeUser.getUsername());
			return "home/index";
		} catch (Exception e) {
			log.error(e);
		}
		return "error";
	}
	
	/*
	 * 用户退出
	 */
	@RequestMapping("/logout")
	public String logout(HttpSession session) throws Exception {
		session.invalidate();
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "login";
	}
}
